/**
  * Copyright (c) CSIRO Australia, 2009
  *
  * @author $Author: jia020 $
  * @version $Id: XmlUtil.java 643 2009-05-20 00:20:55Z jia020 $
  */
package au.csiro.nt.pdsp.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlUtil
{
	public static Document stringToDocument(String theContent)
			throws SAXException, IOException, ParserConfigurationException
	{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		dbf.setIgnoringElementContentWhitespace(true);
		Document doc = dbf.newDocumentBuilder().parse(
				new InputSource(new StringReader(theContent)));
		return doc;

	}

	public static Document fileToDocument(String theInputFileName) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException
	{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		Document doc = dbf.newDocumentBuilder().parse(
				new FileInputStream(theInputFileName));

		return doc;
	}

	public static String documentToString(Document theDoc)
			throws TransformerFactoryConfigurationError
	{
		// Output the resulting document.
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer trans;
		try
		{
			trans = tf.newTransformer();
			StringWriter os = new StringWriter();
			trans.transform(new DOMSource(theDoc), new StreamResult(os));
			return os.toString();
		} catch (TransformerException e)
		{
			e.printStackTrace();
		}

		return null;
	}
}
